import { defineAsyncComponent, watch, inject } from 'vue'
// 状态
import { state } from '@naturefw/nf-state'
import config from '../config/index.js'

const flag = Symbol('nf-router-menu___')

let _router = null

/**
 * 一个简单的路由
 * @returns 
 */
class Router {
  constructor (info) {
    // 设置当前选择的路由
    this.naviId = '' // url里的导航项ID
    this.menuPath = [] // url里的菜单项ID集合，相当于面包屑
    this.baseUrl = info.baseUrl // 基础路径，应对网站的二级目录
    config.baseUrl = info.baseUrl
    // 初始化
    this.setup()
    // 注册组件
    if (info.components) {
      if (Object.keys(info.components).length > 0) {
        this.regComponent(info.components)
      }
    }
  }

  /**
   * 初始化设置
   */
  setup = () => {
    // 当前激活状态
    const { current } = state

    // 监听当前激活的导航项ID，设置url
    watch(() => current.naviId, (key) => {
      // 设置标题
      // document.title = route.title
      // 设置url地址
      window.history.pushState(null, null, this.baseUrl + current.naviId)
    }) // , {immediate: true}
    // 监听面包屑，设置URL
    watch(current.breadcrumb, (bc) => {
      let _title = ''
      let _url = this.baseUrl + current.naviId
      bc.forEach(b => {
        _url += '/' + b.menuId
        _title = b.text + ' ' + _title
      });
      // 设置标题
      document.title = _title
      // 设置url地址
      window.history.pushState(null, null, _url)
    })
  }

  /**
   * 注册组件，以便于在文档里面加载
   * @param {*} components 
   */
  regComponent = (components) => {
    const { comp } = state
    for(let key in components) {
      comp[key] = defineAsyncComponent(components[key])
    }
  }

  // 刷新时依据url加载组件
  refresh = () => {
    const path = window.location.pathname
    if (path === '/' || path === this.baseUrl) {
      // 首页
    } else {
      const arr = path.replace(this.baseUrl, '').split('/')
      // 依据URL进行设置
      this.naviId = arr[0]
      if (arr.length > 1) {
        for (let i = 1; i < arr.length; i++) {
          this.menuPath.push(arr[i])
        }
      }
    }
  }
}

/**
 * 创建简易路由
 */
const createRouter = (info) => {
 
  // 创建路由，
  const router = new Router(info)
  _router = router
  // 判断url，是否需要加载组件
  router.refresh()
 
  // 使用vue的插件，设置全局路由
  return (app) => {
    // 便于模板获取
    app.config.globalProperties.$router = router
    // 便于代码获取
    app.provide(flag, router)
  }
}

const useRouter = () => {
  const tmp = inject(flag)??_router
  return tmp
}

export {
  createRouter,
  useRouter
}